<template>
  <div class="container">
    <el-card class="box-card">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right" v-show="condition">
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item > {{$route.query.name}}</el-breadcrumb-item>
        <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        <el-divider v-show="condition"></el-divider>
      </el-breadcrumb>

      <!-- 内容区一：目录表单搜索区 -->
      <div class="search-box">
        <el-form :inline="true" :model="form" ref="form">
          <el-form-item class="right" label="目录名称">
            <el-input
              @keyup.enter="Query"
              style="width: 180px"
              class="filter-item"
              v-model="form.directoryName"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              placeholder="请选择"
              v-model="form.state"
              style="width: 180px"
              clearable
            >
              <el-option
                v-for="item in status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="ResetForm">清除</el-button>
            <el-button
              :loading="isLoading"
              size="small"
              type="primary"
              @click="Query"
              >搜索</el-button
            >
          </el-form-item>
          <!-- 返回学科 -->
          <div class="box">
            <el-button
              size="small"
              style="margin-left: 10px"
              @click="demo"
              type="text"
              icon="el-icon-edit"
              v-show="condition"
              >返回学科</el-button
            >
            <el-button
              type="success"
              @click="AddComponey"
              size="small"
              class="filter-item fr"
              style="margin-left: 10px"
              icon="el-icon-edit"
            >
              新增目录
            </el-button>
          </div>
        </el-form>
      </div>
      <!-- 数据总计 -->
      <el-alert
        v-if="ResultTip"
        :title="ResultTip"
        type="info"
        class="alert"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 内容区二：表单显示区 -->
      <el-table :data="directorys">
        <el-table-column type="index" label="序号" width="50" prop="id" />
        <el-table-column label="所属学科" prop="subjectName" />
        <el-table-column label="目录名称" prop="directoryName" />
        <el-table-column label="创建者" prop="username" />
        <el-table-column label="创建日期">
          <template slot-scope="scope">
            <span>{{ scope.row.addDate | formatTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="面试题数量" prop="totals" />
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.state == '1'">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>

        <!-- 操作按钮 -->
        <el-table-column label="操作" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="SwitchStatus(scope.row)"
              >{{
                scope.row.state === 0 ? "启用" : "禁用"
              }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="Edit(scope.row.id)"
              :disabled="scope.row.state !== 0"
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.state !== 0"
              v-if="scope.row.status != 'deleted'"
              @click="Delete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination" v-show="total">
        <div class="pages">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="Number(form.page)"
            :total="Number(total)"
            layout=" prev, pager, next,sizes,jumper"
            :page-size="Number(form.pagesize)"
            :page-sizes="[5, 10, 20, 50]"
            :page="Number(form.page)"
            @size-change="handleSizeChange"
          ></el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 新增弹层 -->
    <el-dialog
      :title="isEdit ? '修改目录' : '新增目录'"
      :visible="dialogFormVisible"
      @close="closeRoleDialog"
      width="450px"
    >
      <el-form ref="Form" :model="form1" :rules="rules" label-width="120px">
        <el-form-item label="所属学科" prop="subjectID" >
          <el-select
            placeholder="请选择"
            v-model="form1.subjectID"
            style="width: 80%"
          >
            <el-option
              v-for="item in addlist"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input
            autocomplete="off"
            placeholder="请输入目录名称"
            v-model="form1.directoryName"
            style="width: 80%"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增弹层 -->
        <el-dialog :title="dialogTitle" :visible="dialogFormVisible1" width="20%" @close="closeDialog1">
          <el-form :model="form1" :rules="rules" ref="form">
             <el-form-item label="目录名称" prop="directoryName">
              <el-input v-model="form1.directoryName" style="width: 60%" placeholder="请输入目录名称"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <div style="text-align: right">
              <el-button @click="dialogFormVisible1 = false">取 消</el-button>
              <el-button type="primary" @click="confirmAdd1">确 定</el-button>
            </div>
          </div>
        </el-dialog>
  </div>
</template>

<script>
import {
  list,
  add,
  update,
  detail,
  remove,
  changeState,
  list as getDirectorysAPI
} from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects.js'
import { status } from '@/api/hmmm/constants'
import dayjs from 'dayjs'
export default {
  name: 'Directorys',
  // 格式化日期
  filters: {
    // 格式化入职日期的方法
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  data () {
    return {
      list: [],
      // data: {
      //   state: null,
      //   directoryName: null,
      //   page: 1,
      //   pagesize: 10
      // },
      state: '',
      directorys: [], // 表格数据
      total: 0, // 总数
      form: {
        // 筛选条件的对象
        subjectID: null, // 所属学科
        directoryName: null, // 目录名称
        subjectName: null,
        page: 1,
        pagesize: 10
      },
      form1: {
        subjectID: '', // 所属学科
        // directoryName: '', // 目录名称
        directoryName: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
        // directoryName: [
        //   { required: true, message: '角色描述不能为空', trigger: 'blur' }
        // ]
      },
      isLoading: false,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      isEdit: false, // 是否是编辑
      dialogTitle: '',
      addlist: [],
      condition: false // 显示返回学科
      // condition1: true // 显示目录弹框
    }
  },

  mounted () {
    if (this.$route.query.id) {
      // this.getDirectorysList()
      this.conditionFn()// 面包屑
    } else {
      this.fetchList() // 获取列表
    }
  },
  // 添加侦听器，深度监听
  watch: {
    $route: {
      handler () {
        this.fetchList()
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    status () {
      return status
    },
    ResultTip () {
      return `共 ${this.total} 条记录`
    }
  },
  methods: {
    // 获取列表
    async fetchList () {
      console.log(this.form)
      const res = await list(this.form)
      this.total = res.data.counts
      // console.log(res)
      this.list = res.data.items
      this.directorys = res.data.items
    },
    // 添加目录确定按钮
    async confirmAdd () {
      // const res = await add(this.form.id)
      // console.log(res)
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (!this.isEdit) {
            const res = await add(this.form1)
            console.log(res)
            this.$message.success('新增成功')
          } else {
            const res = await update(this.form1)
            console.log(res)
            this.$message.success('操作成功')
          }
          this.$refs.form.resetFields()
          this.getDirectorysList()
          this.dialogFormVisible = false
        }
      })
      //   if (valid) {
      //     if (this.form.id) {
      //       await update(this.form)
      //     } else {
      //       await add(this.form1)
      //     }
      //     this.$message.success(`${this.form.id ? '编辑' : '新增'}成功`)
      //     this.$refs.form.resetFields()
      //     this.getDirectorysList()
      //     this.dialogFormVisible = false
      //   }
      // })
    },
    // 新增弹层的确认按钮
    async confirmAdd1 () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (!this.isEdit) {
            const res = await add(this.form1)
            console.log(res)
            this.$message.success('新增成功')
          } else {
            const res = await update(this.form1)
            console.log(res)
            this.$message.success('操作成功')
          }
          this.$message.success(`${this.form.id ? '编辑' : '新增'}成功`)
          this.$refs.form.resetFields()
          this.getDirectorysList()
          this.dialogFormVisible1 = false
        }
      })
    },
    // 面包屑
    async conditionFn () {
      if (this.$route.query.id) {
        const res = await list({ subjectID: this.$route.query.id, tagName: this.$route.query.name })
        this.total = res.data.counts
        console.log(res)
        this.list = res.data.items
        this.directorys = res.data.items
        this.condition = true
        // this.condition1 = false
      } else {
        this.condition = false
        // this.condition1 = true
      }
    },
    // 关闭弹窗
    closeRoleDialog () {
      this.form = {
        subjectID: '',
        directoryName: ''
      }
      this.$refs.Form.resetFields()
      this.dialogFormVisible = false
    },
    closeDialog1 () {
      this.dialogFormVisible1 = false
    },
    buildParams () {
      const paramsObj = {}
      const { page, pagesize, directoryName, state } = this.form
      // 如果某一个参数是null,则axios就不会发这个参数
      // 如果某一个参数是""，axios是会发出这个参数
      paramsObj.page = page || null
      paramsObj.pagesize = pagesize || null
      paramsObj.directoryName = directoryName || null
      paramsObj.state = state === '' ? null : state
      return paramsObj
    },

    // 获取所属学科列表
    async getDirectorysList () {
      const res = await simple()
      this.addlist = res.data
      console.log(res.data)
      this.isLoading = true
      // 构建查询参数
      const paramsObj = this.buildParams()
      try {
        const { data: res } = await getDirectorysAPI(paramsObj)
        console.log(res)
        // 获取数据给directorys
        this.directorys = res.items
        // 获取总条数
        this.total = res.counts

        this.isLoading = false
      } catch (err) {
        console.log(err)
        this.isLoading = true
      }
    },

    // 重置表单
    ResetForm () {
      // el 表单组件上有一个resetFields方法
      this.$refs.form.resetFields()
      this.form = {
        directoryName: null,
        state: null,
        page: 1,
        pagesize: 10
      }
      this.fetchList()
    },
    // 搜索区域返回学科
    demo () {
      this.$router.push('/subjects/list')
    },
    // 搜索
    async Query () {
      this.fetchList()
    },
    // 分页
    // 更改每页显示的条数
    handleSizeChange (val) {
      this.form.pagesize = val
      if (this.form.page === 1) {
        this.getDirectorysList()
      }
    },
    // 点击某一页
    handleCurrentChange (curPage) {
      this.form.page = curPage
      this.getDirectorysList()
    },
    // 新增
    AddComponey () {
      // 是否编辑状态
      this.isEdit = false
      this.dialogTitle = '新增目录'
      if (this.$route.query.id) {
        this.dialogFormVisible1 = true
        this.form1.subjectID = Number(this.$route.query.id)
      } else {
        this.dialogFormVisible = true
      }
      this.getDirectorysList() // 获取学科列表渲染页面
      // this.dialogFormVisible = false
    },
    // 修改
    async Edit (id) {
      this.isEdit = true
      const res = await detail({ id: id })
      console.log(res)
      this.form1 = res.data
      this.dialogFormVisible = true
    },

    // 删除
    Delete (userId) {
      this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.doDelete(userId)
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    async doDelete (id) {
      try {
        await remove({ id })
        this.$message.success('成功删除了用户!')
        this.getDirectorysList()
      } catch (err) {
        this.$message.error('删除失败!')
      }
    },
    async doSwitch (row) {
      var data = {
        id: row.id,
        state: Number(!row.state)
      }
      console.log(data)
      await changeState(data)
        .then((response) => {
          this.$message.success('操作成功!')
          this.getDirectorysList(this.form)
        })
        .catch((response) => {
          this.$message.error(status + '失败!')
        })
    },
    // 启用、禁用
    SwitchStatus (row) {
      this.doSwitch(row)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.box-card {
  margin: 10px;
}
.filter-item {
  margin-right: 30px;
}

.alert {
  margin: 0px 0px 15px;
}
.pagination {
  margin-top: 10px;
}
</style>

<style>
.box {
  float: right;
}
.pagination {
  margin: 20px;
  float: right;
}
</style>
